import { _decorator, Node } from 'cc';
import * as cc from 'cc';
import { DialogConfig } from "./DialogConfig";
import LoaderMgr from "../loader/LoaderMgr";
import UIOpenAndClose from '../tween/UIOpenAndClose';
const dialog_index = 100;
/**
 * 弹窗管理器
 * - 要求"预制体名字、预制体节点名字、配置表名字"一致
 * @author 神兽白泽 
 * @description 交流群：415468592
 */
export default class DialogMgr {
    /** 弹窗列表 - 节点池 */
    private static _view_list: Map<string, Node> = new Map();
    /** 弹窗基础路径 */
    private static _base_path = 'moudle/';
    /**
    * 展示弹窗
    * @param dialog_path 弹窗名字
    * @param param 参数
    * @param call_back 回调
    */
    public static async showDialog(dialog_name: keyof typeof DialogConfig, param?: any, call_back?: Function) {
        if (!DialogConfig[dialog_name]) {
            cc.log("show_dialog 弹窗配置不存在：", dialog_name);
            return;
        }
        const node_scene = cc.director.getScene()
        if (!cc.isValid(node_scene)) {
            cc.log("场景不存在！请稍后再试");
            return;
        }
        let node_parent = node_scene.getChildByName('Canvas');
        const dialog_path = this._base_path + DialogConfig[dialog_name];
        let pre_asset = await LoaderMgr.loadAssetByType(dialog_path, cc.Prefab);
        if (!pre_asset) {
            cc.log("预制体不存在：", dialog_path);
            return;
        }
        let node_dialog = cc.instantiate(pre_asset);
        this._view_list.set(dialog_name, node_dialog);
        this.initData(node_dialog, param);
        node_parent.insertChild(node_dialog, dialog_index);
        call_back && call_back(node_dialog);
        return node_dialog;
    }
    /**
    * 关闭弹窗
    * @param dialog_path 弹窗名字
    * @param call_back 回调
    */
    public static closeDialog(dialog_name: keyof typeof DialogConfig, call_back?: Function) {
        const node_dialog = this._view_list.get(dialog_name);
        if (!node_dialog) {
            cc.log("对话框不存在：", dialog_name);
            return false;
        }
        const comp_UIOpenAndClose = node_dialog.getComponent(UIOpenAndClose)
        if (comp_UIOpenAndClose) {
            comp_UIOpenAndClose.playClose(() => {
                this.destroyDialog(node_dialog, dialog_name);
            })
        } else {
            this.destroyDialog(node_dialog, dialog_name);
        }
    }
    private static destroyDialog(node_dialog, dialog_name) {
        node_dialog.destroy();
        this._view_list.delete(dialog_name);
    }
    /**
    * 获取对话框
    * @param dialog_name 对话框名字
    * @returns
    */
    public static getDialog(dialog_name: keyof typeof DialogConfig): Node {
        let node = this._view_list.get(dialog_name);
        return node;

    }
    /**
    * 初始化脚本组件数据
    * @param node_dialog 数据
    * @param param 数据
    */
    private static initData(node_dialog: Node, param: any) {
        const comp_base = node_dialog.getComponent("DialogBase") as any;// 填字符串 避免循环引用
        if (!comp_base) return;
        comp_base.initDialogData(param);
    }
}
